/*
 * @Author: lokei
 * @Date: 2022-10-23 23:33:35
 * @LastEditors: lokei
 * @LastEditTime: 2022-10-24 10:04:19
 * @Description: 
 */
package cn.lokei.task.config.iot;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import cn.lokei.task.config.database.DataSourceConfig;
import cn.lokei.task.config.database.DataSourceContextHolder;
import cn.lokei.task.entity.iot.gateway.Gateway;
import cn.lokei.task.entity.iot.mqtt.MyMqttClient;
import cn.lokei.task.service.iot.gateway.GatewayService;

@Configuration
@AutoConfigureAfter(DataSourceConfig.class)
public class GatewayConfig {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    GatewayService gatewayService;

    @Bean(name = "gatewayClientMap")
    public Map<String, MyMqttClient> initGatewayClients() {
        Map<String, MyMqttClient> gatewayClientMap = new HashMap<String, MyMqttClient>();
        Set<Object> proj_set = redisTemplate.opsForSet().members("proj:saas");
        if (proj_set != null && proj_set.size() > 0) {
            for (Object project : proj_set) {
                JSONObject proj_info = JSON.parseObject(project.toString());
                DataSourceContextHolder.setDataSource(proj_info.getString("pid"));
                try {
                    List<Gateway> gatewayMap = gatewayService.queryOfProj();
                    for (Gateway gateway : gatewayMap) {
                        String key = proj_info.getString("pid") + ":" + gateway.getIdentity() + "_cloud";
                        gatewayClientMap.put(key, new MyMqttClient(key, gateway.getIp()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            List<Gateway> gatewayMap = gatewayService.queryOfProj();
            for (Gateway gateway : gatewayMap) {
                String key = gateway.getIdentity() + "_cloud";
                gatewayClientMap.put(key, new MyMqttClient(key, gateway.getIp()));
            }
        }
        return gatewayClientMap;
    }
}
